<template>
  <div>
    <div>
      <input v-model="keyword" type="text" placeholder="搜索">
    </div>
    <div style="margin-top: 20px;">
      <table>
        <thead>
          <tr>
            <th>物品名</th>
            <th>单价</th>
            <th>数量</th>
            <th>总价</th>
            <th>操作</th>
          </tr>
        </thead>
        <tr v-for="(item, index) in searchData" :key="index">
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="item.num > 0 ? item.num-- : null">-</button>
            {{ item.num }}
            <button @click="item.num < 99 ? item.num++ : null">+</button>
          </td>
          <td>{{ item.num * item.price }}</td>
          <td><button @click="del(index)">删除</button></td>
        </tr>
        <tr>
          <td colspan="4">合计</td>
          <td>{{ totalPrice }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed, ref } from 'vue';
const keyword = ref<string>("");
interface Data {
  name: string,
  price: number,
  num: number
}
const searchData = computed(() => {
  return data.filter((item:Data) =>{
    return item.name.includes(keyword.value);
  })
})

let data = reactive<Data[]>([
  {
    name: "小米14pro",
    price: 4600,
    num: 1
  },
  {
    name: "华为meta60pro",
    price: 6000,
    num: 99
  },
  {
    name: "荣耀100",
    price: 4800,
    num: 99
  }
])

const totalPrice = computed(() => {
  return searchData.value.reduce((prev:number,next:Data) => {
    return prev + next.price * next.num;
  },0);
})

const del = (index:number)=>{
  console.log(index);
  
  searchData.value.splice(index,1)
}
</script>

<style scoped></style>